﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace EnhancedWebControls
{
    /// <summary>
    /// Enhances the Panel Control to be skinnable and appear as an overlay popup
    /// </summary>
    [ParseChildren(false), PersistChildren(true)]
    public class PopUpPanel : CompositeControl
    {
        #region Public Properties
        /// <summary>
        /// Gets or Sets the Css Class applied to the PopUpPanel Header Section when the browser is IE6 or lower
        /// </summary>
        [Category("Appearance"), Localizable(true)]
        public string LegacyHeaderBackgroundCssClass { get; set; }
        /// <summary>
        /// Gets or Sets the Css Class applied to the PopUpPanel Content Section when the browser is IE6 or lower
        /// </summary>
        [Category("Appearance"), Localizable(true)]
        public string LegacyContentBackgroundCssClass { get; set; }
        /// <summary>
        /// Gets or Sets the Css Class applied to the PopUpPanel Footer when the browser is IE6 or lower
        /// </summary>
        [Category("Appearance"), Localizable(true)]
        public string LegacyFooterBackgroundCssClass { get; set; }
        /// <summary>
        /// Gets or Sets the Css Class applied to the PopUpPanel Header Section if the browser is not Legacy
        /// </summary>
        [Category("Appearance"), Localizable(true)]
        public string HeaderBackgroundCssClass { get; set; }
        /// <summary>
        /// Gets or Sets the Css Class applied to the PopUpPanel Content Section if the browser is not Legacy
        /// </summary>
        [Category("Appearance"), Localizable(true)]
        public string ContentBackgroundCssClass { get; set; }
        /// <summary>
        /// Gets or Sets the Css Class applied to the PopUpPanel Footer Section if the browser is not Legacy
        /// </summary>
        [Category("Appearance"), Localizable(true)]
        public string FooterBackgroundCssClass { get; set; }
        /// <summary>
        /// Gets or Sets the IFrame Src to use for supporting Legacy browsers
        /// An Iframe will be used when the browser is IE6 or lower, the src of the Iframe will be null, 
        /// but if the Iframe appears on an SSL page you must provide a blank html file for the src value to avoid SSL errors.
        /// </summary>
        public string LegacyIFrameSrc { get; set; }
        /// <summary>
        /// Gets or Sets the horizontal offset of the Top Left corner of the PopUp, relative to the placement within the document. Positive or Negative values are supported
        /// </summary>
        [Category("Appearance"), Localizable(true)]
        public Unit HorizontalRelativePosition { get; set; }
        /// <summary>
        /// Gets or Sets the vertical offset of the Top Left corner of the PopUp, relative to the placement within the document. Positive or Negative values are supported
        /// </summary>
        [Category("Appearance"), Localizable(true)]
        public Unit VerticalRelativePosition { get; set; }
        /// <summary>
        /// Gets or Sets the Z index of the overlay PopUpPanel set this higher than the default (10) only if you are overlayijng something with a higher z-index
        /// </summary>
        public int PopupZIndex { get; set; }
        public bool Hidden {
            get
            {
                if (ViewState["Hidden"] == null)
                    ViewState["Hidden"] = false;
                return (bool)ViewState["Hidden"];
            }
            set
            {
                ViewState["Hidden"] = value;
            }
        }
        #endregion

        protected override void OnPreRender(EventArgs e)
        {
            EnsureChildControls();
            base.OnPreRender(e);
            ApplyClientScriptsToPage();
        }
        public override void RenderBeginTag(HtmlTextWriter writer)
        {
            
            writer.AddAttribute("id", this.ClientID);
            Style["position"] = "absolute";
            if (Hidden)
                Style["display"] = "none";
            foreach (string k in Style.Keys)
            {
                writer.AddStyleAttribute(k, Style[k]);
            }

            writer.RenderBeginTag(HtmlTextWriterTag.Div);
            writer.AddAttribute("id", this.ClientID + "_popupdiv");
            writer.AddStyleAttribute("position", "relative");
            if (!HorizontalRelativePosition.IsEmpty)
                writer.AddStyleAttribute("left", HorizontalRelativePosition.ToString());
            if (!VerticalRelativePosition.IsEmpty)
                writer.AddStyleAttribute("top", VerticalRelativePosition.ToString());
            writer.AddStyleAttribute("z-index", PopupZIndex.ToString());
            writer.RenderBeginTag(HtmlTextWriterTag.Div);   
            RenderIframeForLegacy(writer); //render IFrame
            if (!string.IsNullOrEmpty(GetHeaderClass()))
            {                
                writer.AddAttribute("class", GetHeaderClass());
                writer.RenderBeginTag(HtmlTextWriterTag.Div); //Begin HeaderDiv
                writer.RenderEndTag(); //End HeaderDiv
            }
            if (!string.IsNullOrEmpty(GetContentClass()))
            {
                writer.AddAttribute("class", GetContentClass());
                writer.RenderBeginTag(HtmlTextWriterTag.Div); //Begin ContentDiv
            }
        }
        public override void RenderEndTag(HtmlTextWriter writer)
        {
            if (!string.IsNullOrEmpty(GetContentClass()))
                writer.RenderEndTag(); //End ContentDiv
            if (!string.IsNullOrEmpty(GetFooterClass()))
            {
                writer.AddAttribute("class", GetFooterClass());
                writer.RenderBeginTag(HtmlTextWriterTag.Div); //Begin FooterDiv
                writer.RenderEndTag(); //End FooterDiv
            }
            writer.RenderEndTag(); //End RelativeDiv
            writer.RenderEndTag(); //End AbsoluteDiv
        }
        private void RenderIframeForLegacy(HtmlTextWriter writer)
        {
            if (!DesignMode && Page.Request.Browser.IsBrowserIE6orLower())
            {
                writer.AddAttribute("id", ClientID + "_iframe");
                writer.AddAttribute("src", LegacyIFrameSrc);
                writer.AddStyleAttribute("position", "absolute");
                writer.AddStyleAttribute("visibility", "hidden");
                writer.AddStyleAttribute("filter", "mask()");
                writer.RenderBeginTag(HtmlTextWriterTag.Iframe);
                writer.RenderEndTag();
            }
        }
        private void ApplyClientScriptsToPage()
        {
            if (!DesignMode && Page.Request.Browser.IsBrowserIE6orLower())
            {
                string MoveIframeScriptKey = "MoveIframeScript";
                string InstanceStartupScript = this.ClientID + "_InstanceStartupScript";
                if (!Page.ClientScript.IsClientScriptBlockRegistered(MoveIframeScriptKey))
                {
                    StringBuilder script = new StringBuilder();
                    script.AppendLine(" movePopUpIframe(divID, frameID){");
                    script.AppendLine("var elem = document.getElementById(divID);");
                    script.AppendLine("var frame = document.getElementById(frameID);");
                    script.AppendLine("frame.style.visibility='visible';");
                    script.AppendLine("frame.style.left = elem.offsetLeft + 'px';");
                    script.AppendLine("frame.style.top = elem.offsetTop + 'px';");
                    script.AppendLine("frame.style.height = elem.offsetHeight + 'px';");
                    script.AppendLine("frame.style.width = elem.offsetWidth + 'px';");
                    script.AppendLine("frame.style.zIndex = elem.style.zIndex - 9;");
                    script.AppendLine("}");
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), MoveIframeScriptKey, script.ToString(), true);
                }
                if (!Page.ClientScript.IsStartupScriptRegistered(MoveIframeScriptKey))
                    ScriptManager.RegisterStartupScript(Page, this.GetType(), MoveIframeScriptKey, "movePopUpIframe('" + ClientID + "_popupdiv','" + ClientID + "_iframe');", true);
            }
        }
        private string GetHeaderClass()
        {
            if (!DesignMode && Page.Request.Browser.IsBrowserIE6orLower() && !string.IsNullOrEmpty(LegacyHeaderBackgroundCssClass))
                return LegacyHeaderBackgroundCssClass;
            else
                return HeaderBackgroundCssClass;
        }
        private string GetFooterClass()
        {
            if (!DesignMode && Page.Request.Browser.IsBrowserIE6orLower() && !string.IsNullOrEmpty(LegacyFooterBackgroundCssClass))
                return LegacyFooterBackgroundCssClass;
            else
             return FooterBackgroundCssClass;
        }
        private string GetContentClass()
        {
            if (!DesignMode && Page.Request.Browser.IsBrowserIE6orLower() && !string.IsNullOrEmpty(LegacyContentBackgroundCssClass))
                return LegacyContentBackgroundCssClass;
            else
                return ContentBackgroundCssClass;
        }
    }
}
